#!/bin/bash

PATH=/home/ampdcp/bin:$PATH
export PATH

if [ `uname -s` != 'Linux' ];then
    printf \
    '
        {	
            "messageCode": "error",
            "message": "no support os type [os: '`uname -s`']",
            "data": []
        }
    '
    exit
fi

ingress_info_file=/tmp/ingress_$$.log


#基于Linux平台的ingress自发现
function linux_ingress_check {
	result=""
	err_msg=""

	#获取ingrss信息
	function get_ingress {
		ingress_tran=$1
		arg2=$2
		kubectl get ingress -A | grep -wv 'NAMESPACE' > $ingress_info_file
		while read LINE
		do
			ingress=`echo $LINE | awk '{print $2}'`
			if test "$ingress" = "$ingress_tran";then
				namespace=`echo $LINE | awk '{print $1}'`
				ingressclass=`echo $LINE | awk '{print $3}'`
				if [ -n $ingressclass -a $ingressclass != "<none>" ]; then
					ingresscontroller=`kubectl -n $namespace describe ingressclass $ingressclass | grep -w 'Controller:'| awk '{print $2}' 2> /dev/null`
				else
					ingresscontroller="<none>"
				fi
				daemon=`echo $LINE | awk '{print $4}'`
				rules_info=`kubectl -n $namespace describe ingress $ingress| grep -wA1 "$daemon" |tail -1 2> /dev/null`
				path=`echo $rules_info| awk '{print $1}'`
				backend=`echo $rules_info | awk '{print $2}'`
				ingress_ip=`kubectl -n ${namespace} describe ingress ${ingress} | grep -w 'Address:'|awk '{print $2}' 2> /dev/null`
				node_ip=`kubectl get pod -A -o wide| grep 'controller' |grep -v "kube-controller-manager" | awk '{print $8}'|sort|uniq 2> /dev/null`
				if [ "$arg2" = "namespace" ]; then
					echo $namespace
					break
				elif [ "$arg2" = "ingressclass" ]; then
					echo $ingressclass
					break
				elif [ "$arg2" = "ingresscontroller" ]; then
					echo $ingresscontroller
					break
				elif [ "$arg2" = "daemon" ]; then
					echo $daemon
					break
				elif [ "$arg2" = "path" ]; then
					echo $path
					break
				elif [ "$arg2" = "backend" ]; then
					echo $backend
					break
				elif [ "$arg2" = "ingress_ip" ]; then
				        if [ -z $ingress_ip ];then
					    echo "<none>"
					else
					    echo $ingress_ip
				        fi
					break
				elif [ "$arg2" = "node_ip" ]; then
					echo $node_ip
					break
				else
					echo "para error"
					exit
				fi
			fi
			
		done < $ingress_info_file
	}

    #资产发现方式0-远程扫描，1-WEB爬虫，2-网络流量分析，3-日志分析，4-Agent，5-登录资产，6-手动导入，7-其他
    function found_typelist() {
		if [[ "$1" = 'err_msg' ]];then
			echo "$err_msg"
			return 1
		else
				echo "Agent"
				return 0
		fi
    }
    #资产发现时间
    function found_type_time() {
        now_time=`date '+%Y%m%d%H%M%S'`
		if [ $? -ne 0 ];then
			err_msg="GET_NOW_TIME_FAILURE"
		fi
		if [ "$1" = 'err_msg' ];then
			echo "$err_msg"
			return 1
		else
			if [ "$now_time" ];then
				echo "$now_time"
				return 0
			else
				return 1
			fi
		fi

    }
	
	#是否打印逗号
	function print_comma {
		if [ $1 -ne $2 ]; then
			echo ","
		fi
	}

	#打印结果
	function return_result {
		#多少个ingress
		ingress_names=(`kubectl get ingress -A | grep -wv 'NAMESPACE' | awk '{print $2}'| xargs`)
		num=`expr ${#ingress_names[*]} - 1`

		printf \
		'
		{	
			"messageCode": "success",
			"message": "",
			"data": [
		'
		#打印每个ingress
		for ((i=0;i<${#ingress_names[*]};i++))
		do
	                ingress_name=${ingress_names[$i]}
			echo \
			'{
				"ciCode": "ingress",
				"attributes": [
					{
						"attrName": "主键",
					    "attrCode": "ingress_name",
					    "attrValue": "'$ingress_name'",
					    "attrFailureReason": "''"
					},{
						"attrName": "命名空间",
					    "attrCode": "namespace",
					    "attrValue": "'`get_ingress $ingress_name namespace`'",
					    "attrFailureReason": "'`get_ingress err_msg`'"
					},{
						"attrName": "ingress类",
						"attrCode": "ingressclass",
						"attrValue": "'`get_ingress $ingress_name ingressclass`'",
						"attrFailureReason": "'`get_ingress err_msg`'"		
					},{
						"attrName": "ingress控制器",
						"attrCode": "ingresscontroller",
						"attrValue": "'`get_ingress $ingress_name ingresscontroller`'",
						"attrFailureReason": "'`get_ingress err_msg`'"		
					},{
						"attrName": "域名",
						"attrCode": "daemon",
						"attrValue": "'`get_ingress $ingress_name daemon`'",
						"attrFailureReason": "'`get_ingress err_msg`'"		
					},{
						"attrName": "路由路径",
						"attrCode": "path",
						"attrValue": "'`get_ingress $ingress_name path`'",
						"attrFailureReason": "'`get_ingress err_msg`'"		
					},{
						"attrName": "路由负载",
						"attrCode": "backend",
						"attrValue": "'`get_ingress $ingress_name backend`'",
						"attrFailureReason": "'`get_ingress err_msg`'"		
					},{
						"attrName": "ingress服务地址",
					    "attrCode": "ingress_ip",
					    "attrValue": "'`get_ingress $ingress_name ingress_ip`'",
					    "attrFailureReason": "'`get_ingress err_msg`'"
					},{
						"attrName": "资产发现方式",
						"attrCode": "found_typelist",
						"attrValue": "'`found_typelist`'",
						"attrFailureReason": "'`found_typelist err_msg`'"		
					},{
						"attrName": "资产发现时间",
						"attrCode": "found_type_time",
						"attrValue": "'`found_type_time`'",
						"attrFailureReason": "'`found_type_time err_msg`'"		
					}
				],
				"relations": [
					{
						"quoteCiCode": "host",
						"relationName": "运行于",
						"quoteInstances": [
							[
								{
									"attrName": "控制器POD运行于主机的IP",
									"attrCode": "ip",
									"attrValue": "'`get_ingress $ingress_name node_ip`'",
									"attrFailureReason": "'`get_ingress err_msg`'"
								}
							]
						]
					}
				]
			}'`print_comma $i $num`''
		done
		echo "]}"
	}
	return_result;
}

#错误定义
function return_error {
	case $1 in 
	'UNKNOW_OS')
		printf \
		'
			{	
				"messageCode": "error",
				"message": "no support os type [os: '`uname -s`']",
				"data": []
			}
		'
		;;
	'NO_INSTANCE')
		printf \
		'
			{	
				"messageCode": "error",
				"message": "no instance",
				"data": []
			}
		'
		;;
	'CMD_EXECUTE_ERROR')
		printf \
		'
			{	
				"messageCode": "error",
				"message": "environment not ready [ps exec error]",
				"data": []
			}
		'
		;;
	'NO_USER_PRIVILEGES')
		printf \
		'
			{	
				"messageCode": "error",
				"message": "no user privileges [current: '`echo $USER`']",
				"data": []
			}
		'
		;;
	esac
}

#自发现入口
function main {
	os_type=`uname -s`
	case ${os_type} in
		'Linux')
			if [ `kubectl version | grep -w 'Server Version:' | wc -l` -gt 0 ] && [ $? -eq 0 ]; then
				linux_ingress_check;
			elif [ `kubectl version | grep -w 'Server Version:' | wc -l` -gt 0 ] && [ $? -ne 0 ]; then
				return_error 'CMD_EXECUTE_ERROR';
			else
				return_error 'CMD_NOT_FOUND';
			fi
			;;
		'*')
			return_error 'UNKNOW_OS';
			;;
	esac
        rm -rf $ingress_info_file
}

main
